package cse474_MultiThreadedHTTPServer.Server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Vector;

import cse474_MultiThreadedHTTPServer.Environment.CustomURI;
import cse474_MultiThreadedHTTPServer.Environment.HtmlResponse;
import cse474_MultiThreadedHTTPServer.Logger.ThreadInfo;

public class HttpServer implements Runnable{
	
	Socket serverSocket;
	int threadId;
	Vector<ThreadInfo> threadInfo;
	
	HttpServer(Socket serverSocket, int threadId, Vector<ThreadInfo> threadInfo) {
		this.serverSocket = serverSocket;
		this.threadId = threadId;
		this.threadInfo = threadInfo;
	}
	
	
	@Override
	public void run() {
		long start = System.currentTimeMillis();
		try {
			PrintStream ps = new PrintStream(serverSocket.getOutputStream());
            BufferedReader in = new BufferedReader(new InputStreamReader(
                                        serverSocket.getInputStream()));
			
			String request = in.readLine();
	//		System.out.println(request);
			CustomURI cUri = new CustomURI(request);
			HtmlResponse response = new HtmlResponse(cUri);
			response.getResponse(ps); //for debug
			in.close();
			ps.close();
			serverSocket.close();
			long end = System.currentTimeMillis();
			threadInfo.add(new ThreadInfo(threadId,start, (int)end-start, request, response.getResponseHeader(), response.getResponseText()));
		} catch (IOException e) {
			System.err.println("asd");
		}
		
//		System.err.println("Thread #"+ threadId +" Stopped: "+this.toString()+" "+System.currentTimeMillis());
	}
	

}
